package com.cencat.framework.security.filter;

import com.cencat.framework.security.model.LoginUser;
import com.cencat.framework.security.service.TokenService;
import com.cencat.framework.security.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    private final JwtUtil jwtUtil;
    private final TokenService tokenService;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                  HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {
        
        // 获取请求中的JWT令牌
        String token = getTokenFromRequest(request);
        
        if (StringUtils.hasText(token) && jwtUtil.validateToken(token)) {
            try {
                // 从令牌中获取用户名
                String username = jwtUtil.getUsernameFromToken(token);
                
                // 从缓存中获取登录用户信息
                LoginUser loginUser = tokenService.getLoginUser(token);
                
                if (loginUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    // 验证令牌有效性
                    tokenService.verifyToken(loginUser);
                    
                    // 创建认证令牌
                    UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 设置到安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    log.debug("用户认证成功: username={}, tenantId={}", username, loginUser.getTenantId());
                }
            } catch (Exception e) {
                log.error("JWT认证失败: {}", e.getMessage());
                // 清除认证信息
                SecurityContextHolder.clearContext();
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    /**
     * 从请求中获取令牌
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader(jwtUtil.getHeader());
        
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(jwtUtil.getTokenPrefix())) {
            return bearerToken.substring(jwtUtil.getTokenPrefix().length());
        }
        
        // 尝试从参数中获取
        String token = request.getParameter("token");
        if (StringUtils.hasText(token)) {
            return token;
        }
        
        return null;
    }
    
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        
        // 不需要过滤的路径
        return path.startsWith("/api/auth/") ||
               path.startsWith("/api/public/") ||
               path.startsWith("/swagger-ui/") ||
               path.startsWith("/v3/api-docs/") ||
               path.equals("/doc.html") ||
               path.startsWith("/webjars/") ||
               path.equals("/favicon.ico");
    }
}